//
//  OrderListViewController.m
//  MeterMart
//
//  Created by ENERGY on 2018/9/16.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "OrderListViewController.h"
#import "OrderListTableViewCell.h"
#import "ListDetailViewController.h"
#import "PhoneRegisterViewController.h"
#import "PhoneRegisterViewController.h"
#import "RetreatApplyViewController.h"
#import "RetreatePostIDViewController.h"
#import "CommonViewController.h"
#import "HotelOrderDetailViewController.h"
#import "WeChatLoginViewController.h"
@interface OrderListViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong)UIView * navView;
@property (nonatomic, strong)UIButton * allListBtn;//全部
@property (nonatomic, strong)UIButton * unpayListBtn;//待付款
@property (nonatomic, strong)UIButton * payedListBtn;//已付款
@property (nonatomic, strong)UIButton * salestoreListBtn;//退货/售后
@property (nonatomic, strong)UITableView * tableView;
@property (nonatomic, strong)NSMutableArray * cellArra;
@property (nonatomic, assign)int currentpage;
@property (nonatomic, strong)NSString * payStatus;//支付状态
@property (nonatomic, strong)NSString * codeString;//微信登录回调code
@property (nonatomic, strong)NSString * ifPay;//1为没交会员钱，0为已交会员钱
@property (nonatomic, strong)NSString * deleteListID;//删除的订单号
@property (nonatomic, strong)NSString * orderStatus;//订单状态
@property (nonatomic, assign)int deletRow;//删除第几条数据
@property (nonatomic, strong)NSString * phoneString;
@property (nonatomic, strong)NSString * tokenString;
- (void)ifLogin;
@end

@implementation OrderListViewController(networking)
//订单数据
- (void)getMyOrderListData{
    NSDictionary * dic = @{
                           @"page":@(self.currentpage),
                           @"size":@"6",
                           @"phone":self.phoneString,
                           @"token":self.tokenString,
                           @"paystatus":self.payStatus
                           };
    [self showprogressHUD];
    [[AFAppDotNetAPIClient sharedClient] POST:@"orderiosApi/index" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if ([responseObject[@"sign"] isEqualToString:@"1"]) {
            if (self.currentpage == 1) {
                [self.cellArra removeAllObjects];
            }
            [self.cellArra addObjectsFromArray:responseObject[@"list"][@"orders"]];
            [self.tableView reloadData];
        }else if ([responseObject[@"sign"] isEqualToString:@"400"]){
            [self ifLogin];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}
//删除订单
- (void)deleteOrderList{
    NSDictionary * dic = @{
                           @"orderid":self.deleteListID,
                           @"paystatus":self.orderStatus,
                           @"phone":self.phoneString,
                           @"token":self.tokenString
                           };
    [self showprogressHUD];
    [[AFAppDotNetAPIClient sharedClient] POST:@"orderiosApi/orderdel" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"sign"] isEqualToString:@"1"]) {
            ShowMessage(responseObject[@"msg"]);
            [self.cellArra removeObjectAtIndex:self.deletRow];
            [self.tableView reloadData];
//            [self.cellArra removeAllObjects];
//            [self getMyOrderListData];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}

@end
@implementation OrderListViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.currentpage = 1;
    if ([[UserModel sharedInstanced].token isEqualToString:@""] || [UserModel sharedInstanced].token == nil || [[UserModel sharedInstanced].token length] == 0 || [[UserModel sharedInstanced].mobile isEqualToString:@""] || [UserModel sharedInstanced].mobile == nil || [[UserModel sharedInstanced].mobile length] == 0) {
        self.tokenString = @"";
        self.phoneString = @"";
    }else{
        self.tokenString = [UserModel sharedInstanced].token;
        self.phoneString = [UserModel sharedInstanced].mobile;
    }
    if ([self.payStatus isEqualToString:@""] || self.payStatus == nil || self.payStatus.length == 0) {
        self.payStatus = @"3";//全部：3、待付款：0、已付款：1、退款：2
    }
    if ([self.payStatus isEqualToString:@"3"]) {
        self.allListBtn.selected = YES;
        self.unpayListBtn.selected = NO;
        self.payedListBtn.selected = NO;
        self.salestoreListBtn.selected = NO;
    }else if ([self.payStatus isEqualToString:@"0"]){
        self.allListBtn.selected = NO;
        self.unpayListBtn.selected = YES;
        self.payedListBtn.selected = NO;
        self.salestoreListBtn.selected = NO;
    }else if ([self.payStatus isEqualToString:@"1"]){
        self.allListBtn.selected = NO;
        self.unpayListBtn.selected = NO;
        self.payedListBtn.selected = YES;
        self.salestoreListBtn.selected = NO;
    }else if ([self.payStatus isEqualToString:@"2"]){
        self.allListBtn.selected = NO;
        self.unpayListBtn.selected = NO;
        self.payedListBtn.selected = NO;
        self.salestoreListBtn.selected = YES;
    }
    [self getMyOrderListData];//网络接口
}
- (instancetype)init{
    if (self = [super init]) {
        //添加观察者
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payStatus:) name:@"payStatus" object:nil];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"我的订单";
    self.view.backgroundColor = getColor(mainColor);
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self.view addSubview:self.navView];
    [self.view addSubview:self.tableView];
}
#pragma mark - init
- (UIView *)navView{
    if (!_navView) {
        _navView = [[UIView alloc] initWithFrame:CGRectMake(0, 1/WIDTH_6_SCALE, SCREEN_WIDTH, 44/WIDTH_6_SCALE)];
        _navView.backgroundColor = [UIColor whiteColor];
        //四个按钮
        for (int i = 0; i<4; i++) {
            UIButton * btn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/4 * i, 0, SCREEN_WIDTH/4, self.navView.height)];
            [self button:btn withBGColor:[UIColor whiteColor] withLayerBorderColor:nil withLayerBorderWith:0 withCornerRadius:0 withMasksToBounds:NO withViwe:_navView];
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [btn setTitleColor:getColor(mainRedColor) forState:UIControlStateSelected];
            btn.titleLabel.font = DEF_FontSize_16;
            btn.tag = 50000 + i;
        }
        self.allListBtn = (UIButton *)[self.navView viewWithTag:50000];
        [self.allListBtn addTarget:self action:@selector(listBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.allListBtn setTitle:@"全部" forState:UIControlStateNormal];
        self.unpayListBtn = (UIButton *)[self.navView viewWithTag:50001];
        [self.unpayListBtn addTarget:self action:@selector(listBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.unpayListBtn setTitle:@"待付款" forState:UIControlStateNormal];
        self.payedListBtn = (UIButton *)[self.navView viewWithTag:50002];
        [self.payedListBtn addTarget:self action:@selector(listBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.payedListBtn setTitle:@"已付款" forState:UIControlStateNormal];
        self.salestoreListBtn = (UIButton *)[self.navView viewWithTag:50003];
        [self.salestoreListBtn addTarget:self action:@selector(listBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.salestoreListBtn setTitle:@"退货/售后" forState:UIControlStateNormal];
        self.allListBtn.selected = YES;
        self.unpayListBtn.selected = NO;
        self.payedListBtn.selected = NO;
        self.salestoreListBtn.selected = NO;
    }return _navView;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.navView.height + 1/WIDTH_6_SCALE, SCREEN_WIDTH, SCREEN_HEIGHT - TABBAR_HEIGHT - self.navView.height - 1/WIDTH_6_SCALE - NAVI_HEIGHT) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = 123/WIDTH_6_SCALE;
        [_tableView registerClass:[OrderListTableViewCell class] forCellReuseIdentifier:NSStringFromClass([OrderListTableViewCell class])];
        _tableView.backgroundColor = getColor(mainColor);
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            self.currentpage = 1;
            [self getMyOrderListData];
        }];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            self.currentpage ++;
            [self getMyOrderListData];
        }];
    }return _tableView;
}
- (NSMutableArray *)cellArra{
    if (!_cellArra) {
        _cellArra = @[].mutableCopy;
    }return _cellArra;
}
#pragma mark - action
//监听payStatus状态
- (void)payStatus:(NSNotification *)notification{
    NSDictionary * dic = notification.userInfo;
    NSLog(@"支付状态：%@", dic[@"payStatus"]);
    self.payStatus = dic[@"payStatus"];
}
- (void)listBtnClick:(UIButton *)sender{
    if ([sender.titleLabel.text isEqualToString:@"全部"]) {
        self.allListBtn.selected = YES;
        self.unpayListBtn.selected = NO;
        self.payedListBtn.selected = NO;
        self.salestoreListBtn.selected = NO;
        self.payStatus = @"3";
    }
    if ([sender.titleLabel.text isEqualToString:@"待付款"]) {
        self.allListBtn.selected = NO;
        self.unpayListBtn.selected = YES;
        self.payedListBtn.selected = NO;
        self.salestoreListBtn.selected = NO;
        self.payStatus = @"0";
    }
    if ([sender.titleLabel.text isEqualToString:@"已付款"]) {
        self.allListBtn.selected = NO;
        self.unpayListBtn.selected = NO;
        self.payedListBtn.selected = YES;
        self.salestoreListBtn.selected = NO;
        self.payStatus = @"1";
    }
    if ([sender.titleLabel.text isEqualToString:@"退货/售后"]) {
        self.allListBtn.selected = NO;
        self.unpayListBtn.selected = NO;
        self.payedListBtn.selected = NO;
        self.salestoreListBtn.selected = YES;
        self.payStatus = @"2";
    }
    self.currentpage = 1;
    [self getMyOrderListData];
}
- (void)ifLogin{
    WeChatLoginViewController * vc = [[WeChatLoginViewController alloc] init];
    UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:vc];
    vc.backHomePageBlock = ^{
        [vc dismissViewControllerAnimated:YES completion:nil];
        [self.tabBarController setSelectedIndex:0];
        [self.navigationController popToRootViewControllerAnimated:YES];
    };
    [self presentViewController:navi animated:YES completion:nil];
}
#pragma mark - tableViewDelegate和tableViewDataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    OrderListTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([OrderListTableViewCell class]) forIndexPath:indexPath];
    cell.model = self.cellArra[indexPath.row];
    __weak typeof (self)weakSelf = self;
    cell.refundSupplyBlock = ^(NSString * myListID) {
        RetreatApplyViewController * vc = [[RetreatApplyViewController alloc] init];
        vc.hidesBottomBarWhenPushed = YES;
        vc.orderID = [weakSelf.cellArra[indexPath.row] objectForKey:@"orderid"];
        [self.navigationController pushViewController:vc animated:YES];
    };
    cell.refundApproveBlock = ^(NSString * myListID) {
        RetreatePostIDViewController * vc = [[RetreatePostIDViewController alloc] init];
        vc.hidesBottomBarWhenPushed = YES;
        vc.orderID = [weakSelf.cellArra[indexPath.row] objectForKey:@"orderid"];
        [self.navigationController pushViewController:vc animated:YES];
    };
    return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.cellArra.count;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([[self.cellArra[indexPath.row] objectForKey:@"businid"] isEqualToString:@"1"]) {
        ListDetailViewController * vc = [[ListDetailViewController alloc] init];
        vc.hidesBottomBarWhenPushed = YES;
        vc.myOrderListStr = [self.cellArra[indexPath.row] objectForKey:@"orderid"];
        vc.payStatus = [self.cellArra[indexPath.row] objectForKey:@"paystatus"];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        HotelOrderDetailViewController * vc = [[HotelOrderDetailViewController alloc] init];
        vc.hidesBottomBarWhenPushed = YES;
        vc.myOrderListStr = [self.cellArra[indexPath.row] objectForKey:@"orderid"];
        vc.payStatus = [self.cellArra[indexPath.row] objectForKey:@"paystatus"];
        [self.navigationController pushViewController:vc animated:YES];
    }
}
//tableView自带的左滑删除
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
// 定义编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}
// 进入编辑模式，按下出现的编辑按钮后,进行删除操作
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView setEditing:NO animated:YES];
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"你确定删除该消息？" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        WS(ws)
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            //删除事件
            ws.deleteListID = [NSString stringWithFormat:@"%@", [ws.cellArra[indexPath.row] objectForKey:@"orderid"]];
            ws.orderStatus = [NSString stringWithFormat:@"%@", [ws.cellArra[indexPath.row] objectForKey:@"paystatus"]];
            ws.deletRow = (int)indexPath.row;
            [ws deleteOrderList];
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}
// 修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}
@end
